/**
 * Created by Administrator on 2017/7/8 0008.
 */
var utils = require('./utils');
var userDao = require('../../dao/userDao');
var disUserDao = require('../../dao/disUserDao');
var fs= require('fs');

var createQR = function (req,res) {
    var sid = req.headers.sid;
    var openid = req.headers.openid;
    if(!openid){
        res.send({
            code:1,
            info:'获取推荐二维码失败,请重试!'
        });
        return;
    }

    userDao.getUserById(openid,null,null, function (err,user) {
        if(user){
            utils.createQr(sid,openid,user.regChannel, function (err) {
                if(err){
                    res.send({
                        code:1,
                        info:'获取推荐二维码失败,请重试!'
                    });
                    return;
                }
                res.send({
                    code:0
                });
            });
        }else {
            res.send({
                code:1,
                info:'获取推荐二维码失败,请重试!'
            });
        }
    });
};

/**
 * distribution
 * @param req
 * @param res
 */
var createDisQR = function (req,res) {
    var uid = req.headers.disuid;
    var openid = req.headers.disopenid;

    if(!openid || !uid){
        res.send({
            code:1,
            info:'获取二维码失败,请重试!'
        });
        return;
    }
    var qrLut = './public/distribution/disQR/'+uid+'.png';
    fs.exists(qrLut, function(flag) {
        if(flag){
            res.send({
                code:0
            });
            return;
        }

        disUserDao.getUserById(openid,null,null, function (err,user) {
            if(user){
                utils.createDisQR(uid,openid,user.regChannel, function (err) {
                    if(err){
                        res.send({
                            code:1,
                            info:'获取二维码失败,请重试!'
                        });
                        return;
                    }
                    res.send({
                        code:0
                    });
                });
            }else {
                res.send({
                    code:1,
                    info:'获取推荐二维码失败,请重试!'
                });
            }
        });
    });
};

var CRPopularizeQR = function () {
    var popularizes = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
    popularizes.forEach(function (num) {
        var regChannel = 'popularize'+num;
        utils.createQr(null,null,regChannel, function (err) {
            if(err){

               console.log('CRPopularizeQR err:',err);
            }
        });
    })


};

exports.createQR = createQR;
exports.createDisQR = createDisQR;
exports.CRPopularizeQR = CRPopularizeQR;
